package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.guns.sys.core.properties.SysConfig;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.modular.system.entity.MouldBoardMsg;
import cn.stylefeng.guns.sys.modular.system.entity.Project;
import cn.stylefeng.guns.sys.modular.system.entity.TaskStatus;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyArchivesMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.ProjectMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.ProjectParam;
import cn.stylefeng.guns.sys.modular.system.model.params.TaskFlowParam;
import cn.stylefeng.guns.sys.modular.system.model.params.TaskStatusParam;
import cn.stylefeng.guns.sys.modular.system.model.result.ProjectResult;
import cn.stylefeng.guns.sys.modular.system.service.*;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiangge
 * @since 2020-09-10
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {

    @Autowired
    private TaskFlowService taskFlowService;
    @Autowired
    private TaskStatusService taskStatusService;
    @Resource
    private TaskService taskService;
    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;
    @Resource
    private SysConfig sysConfig;
    @Resource
    private BtyArchivesMapper btyArchivesMapper;
    @Resource
    private ProjectMapper projectMapper;

    private final int enable=1;
    private final int disable=0;
    @Override
    public void add(ProjectParam param){
        //拼接工程名称
        param.setName(new StringBuilder(param.getProvinceName()).append(param.getCityName()).append(param.getName()).toString());
        Project entity = getEntity(param);
        this.save(entity);

        //更新 taskFlow
        TaskFlowParam taskFlowParam=new TaskFlowParam();
        taskFlowParam.setProId(entity.getId());
        //创建店名对应的taskId   1-店名
        taskFlowParam.setTaskId(1);
        //1提交；2审核未通过；3审核通过
        taskFlowParam.setStatus(1);
        taskFlowParam.setTaskName("店名");
        taskFlowService.add(taskFlowParam);

        //更新 taskStatus
        TaskStatusParam taskStatusParam=new TaskStatusParam();
        taskStatusParam.setProId(entity.getId());
        //创建店名对应的taskId   1-店名
        taskStatusParam.setTaskId(1);
        //1提交；2审核未通过；3审核通过
        taskStatusParam.setStatus(1);
        taskStatusService.add(taskStatusParam);
    }

    @Override
    public void delete(ProjectParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(ProjectParam param){
        Project oldEntity = getOldEntity(param);
        Project newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public ProjectResult findBySpec(ProjectParam param){
        return null;
    }

    @Override
    public List<ProjectResult> findListBySpec(ProjectParam param){
        return null;
    }

    public static void main(String[] args) {
        List<Integer> list=new ArrayList<>();

        list.add(13);
        String join = StringUtils.join(list.toArray(), ",");
        System.out.println(join);

    }
    @Override
    public LayuiPageInfo findPageBySpec(ProjectParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        List<ProjectResult> records = page.getRecords();
        LoginUser currentUser = LoginContextHolder.getContext().getUser();
        List<Long> roleList = currentUser.getRoleList();
        Long role_gczj=1305422420779659266L;//工程总监
        Long role_kfzj=1305422111420379138L;//开发总监
        Long role_yyzj=1305422678196678657L;//营运总监
        Long role_kfry=1305313791343853569L;//开发人员
        List<Integer> kfts = taskService.listIdsByRole(role_kfry);
        String kf_taskids=StringUtils.join(kfts.toArray(), ",");//暂不关联工程

        List<Integer> gczj_ts = taskService.listIdsByRole(role_gczj);
        String gczj_taskids=StringUtils.join(gczj_ts.toArray(), ",");

        List<Integer> kfzj_ts = taskService.listIdsByRole(role_kfzj);
        String kfzj_taskids=StringUtils.join(kfzj_ts.toArray(), ",");

        List<Integer> yyzj_ts = taskService.listIdsByRole(role_yyzj);
        String yyzj_taskids=StringUtils.join(yyzj_ts.toArray(), ",");
        for(ProjectResult rs:records){
            Integer proid = rs.getId();
            //根据角色获取任务ids
            //获取开发人员任务完成情况
            List<TaskStatus> kf_taskStatusList = taskStatusService.listBytaskids(proid, kf_taskids);
            //获取工程总监任务完成情况

            List<TaskStatus> gczj_taskStatusList = taskStatusService.listBytaskids(proid, gczj_taskids);
            //获取开发总监任务完成情况
            List<TaskStatus> kfzj_taskStatusList = taskStatusService.listBytaskids(proid, kfzj_taskids);
            //获取营运总监任务完成情况
            List<TaskStatus> yyzj_taskStatusList = taskStatusService.listBytaskids(proid, yyzj_taskids);
            /*if(yyzj_taskids.split(",").length==yyzj_taskStatusList.size()){//yyzj已确认
                rs.setGcedit(disable);
                rs.setSwedit(disable);
                if(roleList.contains(role_gczj)||roleList.contains(role_yyzj)||roleList.contains(role_kfry)){//工程总监/营运总监/开发人员
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                }else if(roleList.contains(role_kfzj)){//开发总监
                    rs.setGcbtn(disable);
                    rs.setSwbtn(enable);
                }else{
                    rs.setGcbtn(disable);
                    rs.setSwbtn(disable);
                }
            }else*/ if(gczj_taskids.split(",").length==gczj_taskStatusList.size() && kfzj_taskids.split(",").length==kfzj_taskStatusList.size()){//kfzj+gczj OK
                rs.setGcedit(disable);
                rs.setSwedit(disable);
                if(roleList.contains(role_gczj)||roleList.contains(role_yyzj)||roleList.contains(role_kfry)){//工程总监/营运总监/开发人员
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                }else if(roleList.contains(role_kfzj)){//开发总监
                    rs.setGcbtn(disable);
                    rs.setSwbtn(enable);
                }else{
                    rs.setGcbtn(disable);
                    rs.setSwbtn(disable);
                }
            }else if(kf_taskids.split(",").length==kf_taskStatusList.size()){//开发人员任务完成
                rs.setGcedit(disable);
                rs.setSwedit(disable);
                if(roleList.contains(role_gczj)||roleList.contains(role_kfry)){//工程总监/开发人员
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                }else if(roleList.contains(role_kfzj)){//开发总监
                    rs.setGcbtn(disable);
                    rs.setSwbtn(enable);
                }else{
                    rs.setGcbtn(disable);
                    rs.setSwbtn(disable);
                }
            }else{//kf人员未完成
                if(roleList.contains(role_kfry)){//开发人员
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                    rs.setGcedit(enable);
                    rs.setSwedit(enable);
                }if(roleList.contains(role_kfzj)){//开发总监
                    // 判断店名和商务条件是否完成
                    String kf_taskids2="1,2";
                    List<TaskStatus> kf_taskStatusList2 = taskStatusService.listBytaskids(proid, kf_taskids2);
                    if(kf_taskids2.split(",").length==kf_taskStatusList2.size()) {//店名和商务条件完成
                        rs.setSwbtn(enable);
                    }else{
                        rs.setSwbtn(disable);
                    }
                    rs.setGcbtn(disable);
                    rs.setGcedit(disable);
                    rs.setSwedit(disable);
                }else{
                    rs.setGcbtn(disable);
                    rs.setSwbtn(disable);
                }
            }

        }
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(ProjectParam param){
        return null;
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private Project getOldEntity(ProjectParam param) {
        return this.getById(getKey(param));
    }

    private Project getEntity(ProjectParam param) {
        Project entity = new Project();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    @Override
    public void pushMsg2KFZJ(Integer proid){
        // 判断店名和商务条件是否完成
        String kf_taskids2="1,2";
        List<TaskStatus> kf_taskStatusList2 = taskStatusService.listBytaskids(proid, kf_taskids2);
        if(kf_taskids2.split(",").length==kf_taskStatusList2.size()) {//店名和商务条件完成
           //获取开发总监openid
            Project pro = getById(proid);
            String[] strs={"开发总监确认","待审核", DateUtil.getNow(),"等待审核"};
            JSONObject param = weChatSendTempMsgService.setTempParam(pro.getName(), "请尽快处理！", strs);
            String[] openids=sysConfig.getKfzjOpenid().split(";");
            weChatSendTempMsgService.sendmsg(openids,"",param);
        }
    }

    @Override
    public void pushMsg2GCZJ(Integer proid){
        // 判断店名、商务条件、工程条件是否完成
        String kf_taskids3="1,2,3";
        List<TaskStatus> kf_taskStatusList3 = taskStatusService.listBytaskids(proid, kf_taskids3);
        if(kf_taskids3.split(",").length==kf_taskStatusList3.size()) {//条件完成
            Project pro = getById(proid);
            String[] strs={"工程总监确认","待审核", DateUtil.getNow(),"等待审核"};
            JSONObject param = weChatSendTempMsgService.setTempParam(pro.getName(), "请尽快处理！", strs);
            String[] openids=sysConfig.getGczjOpenid().split(";");
            weChatSendTempMsgService.sendmsg(openids,"",param);
        }
    }

    @Override
    public void pushMsg2YYZJ(Integer proid){
        // 判断工程总监,开发总监确认 是否完成
        String taskids="5,6";
        List<TaskStatus> taskStatusList = taskStatusService.listBytaskids(proid, taskids);
        if(taskids.split(",").length==taskStatusList.size()) {//条件完成
            Project pro = getById(proid);
            String[] strs={"营运总监确认","待审核", DateUtil.getNow(),"等待审核"};
            JSONObject param = weChatSendTempMsgService.setTempParam(pro.getName(), "请尽快处理！", strs);
            String[] openids=sysConfig.getYyzjOpenid().split(";");
            weChatSendTempMsgService.sendmsg(openids,"",param);
        }
    }

    @Override
    public void saveGcyyjl(ProjectParam record) {
        if(ToolUtil.isOneEmpty(record,record.getId(),record.getYyjl())){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //根据yyjl查找手机
        String tel = btyArchivesMapper.getTelByName(record.getYyjl());
        if(ToolUtil.isNotEmpty(tel)){//如果为空则保存姓名
            record.setYyjl(tel);
        }
        baseMapper.updateProjectByCondition(record);
    }


    @Override
    public void saveGcDd(ProjectParam record) {
        if(ToolUtil.isOneEmpty(record,record.getId(),record.getDd())){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //根据dd查找手机
        String tel = btyArchivesMapper.getTelByName(record.getDd());
        if(ToolUtil.isNotEmpty(tel)){//如果为空则保存姓名
            record.setDd(tel);
        }
        baseMapper.updateProjectByCondition(record);
    }

    /**
     * 查询微信推送督导及营运经理
     * @return
     */
    @Override
    public Map<String, String> selectDd(Integer proid) {
        Project project = projectMapper.selectDd(proid);
        //督导姓名
        String dd = project.getDdName();
        //营运经理
        String yyjl = project.getYyjlName();
        Map<String, String> map = new HashMap<>();
        map.put("dd",dd);
        map.put("yyjl",yyjl);
        return map;
    }

    /**
     * 查询督导列表
     */
    @Override
    public List<Map> selectDdList() {
        //获取当前登录者的姓名
        String name = LoginContextHolder.getContext().getUser().getName();
        //查询该营运经理对应的督导
        return projectMapper.selectDdList(name);
    }

    /**
     * 查询营运经理列表
     * @return
     */
    @Override
    public List<Map> selectYyjlList() {
        return projectMapper.selectYyjlList();
    }

    /**
     * 查询表格内容列表
     * @return
     */
    @Override
    public List<MouldBoardMsg> selectMsgList(Integer proId, Integer mouldId) {
        return projectMapper.selectMsgList(proId,mouldId);
    }


}
